package main

import (
	"fmt"
    "time"
    "net"
    "os"
)

type bconn struct {
	conn 		net.Conn
	ch 			chan []byte
	established bool
	lcnt 		int
	speed 		int
	lastspeed 	int
}

func HandleTcpRec(a []byte) {
	fmt.Println("tcp rec", len(a))
}

func (b *bconn) recv() {
	//var cmdOnline= [2]byte{0x00, 0x00}
	var buf [1460]byte
	syn := make(chan struct{})
    defer close(syn)
    go b.sendv(syn)
   // s.conn.Write(cmdOnline[0:])
    for {
	    n, err := b.conn.Read(buf[0:])
	    if err != nil {
			return
	    }
		HandleTcpRec(buf[:n])
	    b.lcnt += n
    }
}

func (b *bconn) sendv(syn chan struct{}) {
	var	cmdHeartTick= [3]byte{0x01, 0x00, 0x00}
	hearttick := time.Tick(3000 * time.Millisecond)
	tcnt1m := time.Tick(120 * time.Second)
    for {
        select {
        case _, ok := <-syn:
            if !ok {
            	return
            }
        case msg, ok := <-b.ch:
        	if ok {
				_, err := b.conn.Write(msg)
	        	if err != nil {
					return
	        	}
            }
        case <-hearttick: 
        	_, err := b.conn.Write(cmdHeartTick[:]) /*heartick*/
        	if err != nil {
				return
	        }
        	b.speed = b.lcnt/3
        	b.lcnt = 0
        	off := b.speed - b.lastspeed
        	if off >= 3 * 1024 || off <= -3 * 1024 {
				fmt.Printf("节目流量变化：%dB/s -> %dB/s\r\n", b.lastspeed, b.speed)	
        	}
        	b.lastspeed= b.speed
        case <-tcnt1m: 
        	if b.speed > 0 {
				//log.Printf("节目流量：%dKB/s\r\n", speed)	
				//fmt.Printf("节目流量：%dKB/s\r\n", speed)	
        	}
        }
    }
}

func (b *bconn) run(remoteIp string) {
	addr, err := net.ResolveTCPAddr("tcp4", remoteIp)
	if err != nil {
        fmt.Println("ResolveTCPAddr error:", err.Error())
        os.Exit(1)
    }
    b.ch = make(chan []byte, 1)
    for {
        b.conn, err = net.DialTCP("tcp", nil, addr)
        if err == nil {
            defer b.conn.Close()
            b.established = true
            fmt.Println("节目网络连接成功", addr)
            load :=  "hello"
			b.ch <- []byte(load)
            b.recv()
            fmt.Println("节目网络断开")
            b.established = false
            
        }
        time.Sleep(2 * time.Second)
    }
}

func main () {
	var b bconn
	b.run("192.168.251.170:8080")

}








